package ideamaps;

import java.util.List;
import java.util.Map;

import ideamaps.settings.Custlist;
import ideamaps.settings.CustlistCache;
import ideamaps.settings.CustlistItem;
import ideamaps.settings.CustlistManager;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;


import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.support.WebApplicationContextUtils;

public class StartupListener extends ContextLoaderListener implements ServletContextListener {

	@Override
	public void contextDestroyed(ServletContextEvent event) {
		
		
	}

	@Override
	public void contextInitialized(ServletContextEvent event) {

		ServletContext servletContext = event.getServletContext();
		servletContext.setAttribute("config", Config.getInstance());
		
		
		CustlistManager custlistManager = getCustlistManager(servletContext);
		
		List<Custlist> l = custlistManager.getAll();
		for(Custlist custlist:l){
			List<CustlistItem> items = custlistManager.find("from CustlistItem ci where ci.custlist.id=?",custlist.getId());
			custlist.setItems(items);
		}
		
		CustlistCache.init(l);
		
		//init custlist
		Map<String,Custlist> m =  CustlistCache.getCache();
		
		for(Map.Entry<String, Custlist> entry : m.entrySet())  {   
			servletContext.setAttribute(entry.getKey().trim(), entry.getValue().getItems());
		} 
	}
	
	
	private CustlistManager getCustlistManager(ServletContext servletContext){
		return (CustlistManager)WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext).getBean("custlistManager");
	}


}
